import React from 'react'
import { connect } from 'dva'
import { Form, Modal, Button, Icon, Dropdown, Menu, Row, Input, Table, Col, Radio, Select} from 'antd'
import ListPage from 'widget/PageTmpl/ListPage'
import { mapStateToProps } from 'utils/view_utils'
import { Link, hashHistory } from 'dva/router'
// import { div } from '../../../../utils/caculate';
import config from '../../../../config/config'
import styles from './userListStyle.less'

const FormItem = Form.Item;
const Option = Select.Option;

const formItemLayout1 = {
    labelCol: {span: 9}, wrapperCol: {span: 15}
};
/*
 * 用户列表
 * @author 廖玉宾
 * @time 未知
 * */
const routeView = ({ dispatch, model, form }) => {

	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
	const { modelObj, namespace } = model
	let {showAddVisible,dataSource } = modelObj
	const menu = (
		<Menu onClick={(e) => { againConfirmation(e.key) }}>
			<Menu.Item key="delete">批量删除</Menu.Item>
			<Menu.Item key="forbid">批量禁用</Menu.Item>
			<Menu.Item key="open">批量启用</Menu.Item>
		</Menu>
	)

	//弹框列表
    const columns = [
        {title: '', dataIndex: 'color2', key: 'color2',width:60,
            render :(text,record,index)=>{
                return (<div>
                    <Radio checked={record.checked} onChange = {(e)=>{
                        dataSource.map((x,i)=>{
                          x.checked = i == index
                        })
                        dispatch({
                            type: `${namespace}/updateStore`,
                            payload: dataSource
                        })
                    }
                    } > </Radio>
				</div>)
            }
        },
        {title: '编号', dataIndex: 'color', key: 'color',width:80,
		},
        {title: '姓名', dataIndex: 'size', key: 'size',width:100,
        },
        {title: '性别', dataIndex: 'sellPrice', key: 'sellPrice',width:60,},
        {title: '手机号', dataIndex: 'sellPrice1', key: 'sellPric1',width:130,},
        {title: '身份证号码', dataIndex: 'modGroupBookingPrice', key: 'modGroupBookingPrice',width:130,
        },
      {
        title: '角色', dataIndex: 'sellPrice2', key: 'sellPric2', width: 160,
        render: (text, record) => {
          return (
            <div>
              <Select
                disabled={!record.checked}
                mode="multiple"
                style={{width: 150}}
                placeholder="Please select"
                defaultValue={['a10', 'c12']}
                onChange={(v) => {
                  handleChange(v)
                }}
              >
                {dataSource && dataSource.map((item, index) => {
                  return <Option key={index} value={item.color}>{item.size}</Option>
                })}
              </Select>
            </div>
					)
        }
      },
	]

	//选中的角色
    function handleChange(value) {
        console.log(`selected ${value}`);
    }

	function onSubmit() {
		console.log("确认")
    }

	// 再次确认提示框
	function againConfirmation(actionType, actionId, modalTheme = 'confirm') {
		// 设置传入的参数
		const params = { id: actionId ? actionId : modelObj.biz.selectedRows.map(item => item.id).join(',') };

		// 当为批量操作状态时，需要额外传入参数 -- 1：批量启用；2：批量禁用
		if (['forbid', 'open'].includes(actionType)) {
			params.status = actionType === 'forbid' ? 2 : 1;
		}

		// 根据当前弹出框的操作类型，设置调用的方法
		const funName = ['singleDelete', 'delete'].includes(actionType) ? 'batchDelete' : 'batchUpdate';

		// 设置提示信息，删除时的提示信息由接口返回
		const tips = actionType === 'delete' ? '删除' : actionType === 'forbid' ? `禁用` : `启用`;

		Modal[modalTheme]({
			title: '友情提示',
			content: `确定要${tips}选中的用户吗？`,
			maskClosable: true,
			okText: '确定', cancelText: '取消',
			onOk: () => {
				dispatch({ type: `${namespace}/${funName}`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
			}
		})
	}

	function fresh() {
		// 刷新列表数据
		modelObj.biz.refreshListDatas(true)
	}

	function changeStatus(item) {
		let status = 1;
		if (item.status == 1) { status = 2 }
		dispatch({
			type: `${namespace}/changeStatus`,
			payload: {
				params: { id: item.id, status: status },
				cb: () => { fresh() }
			}
		})
	}
  
  function renderSearchFields () {
    let arr = [
      {
        en_name: 'realName',
        zh_name: '姓名',
        elem_type: 'Input',
        elem_valid_type: 'string'
      },
      {
        en_name: 'phone',
        zh_name: '手机号',
        elem_type: 'Input',
        elem_valid_type: 'string'
      },
      {
        en_name: 'roleName',
        zh_name: '角色',
        elem_type: 'Input',
        elem_valid_type: 'string'
      },
      {
        en_name: 'status',
        zh_name: '状态',
        elem_type: 'Select',
        elem_valid_type: 'string',
        cmpt_items: [
          {'label': '启用', 'value': '1'},
          {'label': '禁用', 'value': '2'}
        ],
      }
    ]
    //组织管理
    
    return arr
  }
  
  function renderTableFields () {
    let arr = [
      {
        en_name: 'name',
        zh_name: '姓名',
      },
      {
        en_name: 'phone',
        zh_name: '手机号',
        
      },
      {
        en_name: 'roleList',
        zh_name: '角色',
        width: 416,
        render: (text, record) => {
          // if (config.appId == 4 && !!record.orgName) {
          // 	return <div title={'组织管理员'}>组织管理员</div>
          // }
          let arr = []
          record.roleList && record.roleList.forEach((e) => {
            let name = e.name
            if (e.status == 2) { name && arr.push(name) }
          })
          return <div className={styles.longEllipsis} title={arr.join(',')}> {arr.join(',')}</div>
        }
      },
      {
        en_name: 'status',
        zh_name: '状态',
        render: (text, record) => {
          return <div>{record.status == 1 ? '启用' : '禁用'}</div>
        }
      }
    ]
    
    return arr
  }

	let pageProps = {
		ui: {
            api_url: "admin/estate/list",
            method: "POST",
            headers: {
                "Content-type": "application/json"
            },
            app: "",
            params: "pageNo=1&pageSize=10",
            mockData: null,
			search_bar: {
				fields: renderSearchFields()
			},
			action_bar: [
				{
					func_name: "onBatDel",
					label: "批量删除",
					rowSelection: (selectedRowKeys, selectedRows) => { },
					render: () => {
						let isDisabled = true;
						if (modelObj.biz && modelObj.biz.selectedRows && modelObj.biz.selectedRows.length != 0) {
							isDisabled = false;
						}
						return (
							<Dropdown overlay={menu} disabled={isDisabled}>
								<Button>
									批量操作 <Icon type="down" />
								</Button>
							</Dropdown>
						)
					}
				},
				{
					func_name: "onAdd",
					label: "新增",
					type: "primary",
					icon: "plus",
					onClick: (e) => {
                        dispatch({
                            type: `${namespace}/updateStore`,
                            payload: {showAddVisible:true}
                        })
					}
				}
			],
			// 数据表格
			table: {
				fields: renderTableFields(),
				 // scroll: { x: 1450 },
				action_props: {
					width: 160,
				// 	fixed: 'right',
				},
				actions: [{
					func_name: "onEdit",
					label: "",
					render: (item) => {
						return <a href='javascript:;' onClick={e => hashHistory.push({
							pathname: MODULE_TO_ROUTES[namespace].urlArray[0],
							query: { type: 'edit', id: item.id }
						})}>编辑</a>
					}
				},
				{
					func_name: "onToggleStatus",
					render: (item) => {
						return <a href='javascript:;' onClick={e => { changeStatus(item) }}>{item.status == 1 ? '禁用' : '启用'}</a>
					}
				},
				{
					func_name: "onDelete",
					label: "删除",
					api_url: `${config.sysApiHeader}/v1/pearlriver/comm/user/delete`,
					params: 'id=',
					method: 'DELETE'
				}
				],
			}
		}
	}

	if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/setFormVal`,
				payload: biz
			})
		}
	}
	//关闭弹出
	function handleCancel() {
        dispatch({
            type: `${namespace}/updateStore`,
            payload: {showAddVisible:false}
        })
    }


	return <div className={styles.userList}>
        {
            showAddVisible &&<Modal
                title={"新增用户"}
                visible={true}
				width={1000}
                okText="确认"
                cancelText="取消"
                onOk={()=>onSubmit()}
                onCancel={()=>handleCancel()}
            >
                <div>
                    <Row>
						<Col span={6}>
                            <FormItem {...formItemLayout1} label="姓名" hasFeedback>
                                <Input onChange={e => inputChange('name', e.target.value)}/>
                            </FormItem>
						</Col>
                        <Col span={6}>
                            <FormItem {...formItemLayout1} label="身份证号" hasFeedback>
                                <Input onChange={e => inputChange('name2', e.target.value)}/>
                            </FormItem>
                        </Col>

                        <Col span={6}>
                            <FormItem {...formItemLayout1} label="手机号" hasFeedback>
                                <Input onChange={e => inputChange('name1', e.target.value)}/>
                            </FormItem>
                        </Col>

                        <Col span={6}>
							<Button style={{    marginTop: 4,marginLeft: 32}} onClick={()=>{
							console.log("搜索")
                            }}>搜索</Button>
                        </Col>


					</Row>
                </div>

                <div>
                    <Table columns={columns}
                           dataSource={dataSource}
                           onRow={(record, index) =>{onClick:()=> {
                               dataSource.map((x,i)=>{
                                   if(i == index){
                                       x.checked = true
                                   }else {
                                       x.checked = false
                                   }
                               })
                               dispatch({
                                   type: `${namespace}/updateStore`,
                                   payload: dataSource
                               })
                           }}}

                    />
                </div>
            </Modal>
        }
		<ListPage pageProps={pageProps} />
	</div>

}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
